package com.example.miniodownload.service;

import io.minio.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class MinioService {
    private MinioClient minioClient;

    public void initializeMinioClient(String endpoint, String accessKey, String secretKey) {
        try {
            minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
        } catch (Exception e) {
            log.error("初始化MinIO客户端失败", e);
            throw new RuntimeException("无法连接到MinIO服务器");
        }
    }

    public List<String> listBuckets() {
        try {
            List<String> bucketNames = new ArrayList<>();
            for (Bucket bucket : minioClient.listBuckets()) {
                bucketNames.add(bucket.name());
            }
            return bucketNames;
        } catch (Exception e) {
            log.error("获取桶列表失败", e);
            throw new RuntimeException("获取桶列表失败");
        }
    }

    public void downloadBucket(String bucketName, String downloadPath, DownloadProgressCallback callback) {
        try {
            Iterable<Result<Item>> objects = minioClient.listObjects(
                    ListObjectsArgs.builder().bucket(bucketName).recursive(true).build());

            for (Result<Item> result : objects) {
                Item item = result.get();
                String objectName = item.objectName();
                File targetFile = new File(downloadPath, objectName);

                // 确保目标目录存在
                targetFile.getParentFile().mkdirs();

                minioClient.downloadObject(
                        DownloadObjectArgs.builder()
                                .bucket(bucketName)
                                .object(objectName)
                                .filename(targetFile.getAbsolutePath())
                                .build());

                if (callback != null) {
                    callback.onProgress(objectName);
                }
            }
        } catch (Exception e) {
            log.error("下载桶内容失败", e);
            throw new RuntimeException("下载失败: " + e.getMessage());
        }
    }

    public interface DownloadProgressCallback {
        void onProgress(String objectName);
    }
}